package com.mengxiangnongfu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mengxiangnongfu.constants.Constants;
import com.mengxiangnongfu.domain.DictData;
import com.mengxiangnongfu.dto.DicDataDto;
import com.mengxiangnongfu.dto.DicTypeDto;
import com.mengxiangnongfu.mapper.DictDataMapper;
import com.mengxiangnongfu.vo.DataGridView;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mengxiangnongfu.domain.DictType;
import com.mengxiangnongfu.mapper.DictTypeMapper;
import com.mengxiangnongfu.service.DictTypeService;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Exception.class)
public class DictTypeServiceImpl implements DictTypeService {

    @Resource
    private DictTypeMapper dictTypeMapper;

    @Resource
    private DictDataMapper dictDataMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public DataGridView loadAllDic() {
        QueryWrapper<DictType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(DictType.COL_STATUS, Constants.STATUS_TRUE);
        List<DictType> dictTypes = this.dictTypeMapper.selectList(queryWrapper);
        return new DataGridView((long) dictTypes.size(), dictTypes);
    }

    @Override
    public DataGridView loadDicByPage(DicTypeDto dicTypeDto) {
        //创建分页
        Page<DictType> page = new Page<>(dicTypeDto.getPageNum(), dicTypeDto.getPageSize());
        QueryWrapper<DictType> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(dicTypeDto.getDictName()), DictType.COL_DICT_NAME, dicTypeDto.getDictName());
        queryWrapper.eq(StringUtils.isNotBlank(dicTypeDto.getDictType()), DictType.COL_DICT_TYPE, dicTypeDto.getDictType());
        queryWrapper.eq(StringUtils.isNotBlank(dicTypeDto.getStatus()), DictType.COL_STATUS, dicTypeDto.getStatus());
        queryWrapper.ge(dicTypeDto.getBeginTime() != null, DictType.COL_CREATE_TIME, dicTypeDto.getBeginTime());
        queryWrapper.le(dicTypeDto.getEndTime() != null, DictType.COL_CREATE_TIME, dicTypeDto.getEndTime());
        this.dictTypeMapper.selectPage(page, queryWrapper);
        return new DataGridView(page.getTotal(), page.getRecords());
    }

    @Override
    public Integer insertDic(DicTypeDto dicTypeDto) {
        DictType dictType = new DictType();
        BeanUtil.copyProperties(dicTypeDto, dictType);
        dictType.setCreateBy(dicTypeDto.getSimpleUser().getUserName());
        dictType.setCreateTime(DateUtil.date());
        return this.dictTypeMapper.insert(dictType);
    }

    @Override
    public Boolean dicExist(Long dicId, String dicType) {
        //传递的dicId如如果为null置为-1
        dicId = (dicId == null) ? -1L : dicId;
        QueryWrapper<DictType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(DictType.COL_DICT_TYPE, dicType);
        DictType dictType = this.dictTypeMapper.selectOne(queryWrapper);
        if (null == dictType || dicId.intValue() != dictType.getDictId().intValue()) {
            return false;
        }
        return true;
    }

    @Override
    public Integer modifyDic(DicTypeDto dicTypeDto) {
        DictType dictType = new DictType();
        BeanUtil.copyProperties(dicTypeDto, dictType);
        return this.dictTypeMapper.updateById(dictType);
    }

    @Override
    public Integer removeDic(Long[] dicIds) {
        List<Long> ids = Arrays.asList(dicIds);
        if (null != ids && ids.size() > 0) {
            return this.dictTypeMapper.deleteBatchIds(ids);
        }
        return -1;
    }

    @Override
    public DictType getDictTypeById(Serializable dicId) {
        return this.dictTypeMapper.selectById(dicId);
    }

    /**
     * 同步缓存
     * 1.查询可用的字典数据
     * 2.根据字典的类型查询字典
     * 3.把字典数据生成json传到redis
     * 设计思路
     * 设计key dict:type
     */
    @Override
    public void dictCacheAsync() {
        QueryWrapper<DictType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(DictType.COL_STATUS, Constants.STATUS_TRUE);
        List<DictType> dictTypes = this.dictTypeMapper.selectList(queryWrapper);
        for (DictType dictType : dictTypes) {
            QueryWrapper<DictData> dictDataQueryWrapper = new QueryWrapper<>();
            dictDataQueryWrapper.eq(DictData.COL_STATUS, Constants.STATUS_TRUE);
            dictDataQueryWrapper.eq(DictData.COL_DICT_TYPE, dictType.getDictType());
            dictDataQueryWrapper.orderByAsc(DictData.COL_DICT_SORT);
            List<DictData> list = dictDataMapper.selectList(dictDataQueryWrapper);
            String value = JSON.toJSONString(list);
            stringRedisTemplate.opsForValue().set(Constants.DICT_REDIS_PROFIX + dictType.getDictType(), value);
        }
    }
}
